<?php
// +----------------------------
// | Created by PhpStorm
// +----------------------------
// | Author: YnnSon
// +----------------------------
namespace app\api\controller\v1;

use app\api\model\MemberLog;
use app\api\model\Order as OrderModel;
use app\api\model\RefundLog;
use app\api\service\Order as OrderService;
use app\api\service\Order2 as Order2Service;
use app\api\validate\OrderValidate;
use app\api\validate\ParameterMustBePositiveInteger;
use app\lib\enum\MemberLogEnum;
use app\lib\enum\OrderStatusEnum;
use app\lib\enum\PaymentEnum;
use app\lib\enum\PayStatusEnum;
use app\lib\enum\RefundStatusEnum;
use app\lib\exception\SuccessMessage;
use think\Config;
use think\Db;
use think\Exception;
use think\Log;
use think\Request;
use Yurun\Util\HttpRequest;

/**
 * 订单
 * Class Order
 * @package app\api\controller\v1
 */
class Order extends BaseController
{
    /**
     * @desc 检查用户权限
     */
    protected $beforeActionList = [
        'checkUserScope' => ['only' => 'getorderlist,getorderdetail,cancelorder,getrefundlist,getrefunddetail,updaterefundstatus,placeorder'], // 方法名必须全部小写，逗号中间不能有空格！！！
    ];

    /**
     * @Desc 根据订单状态查询订单
     *
     * @param        $status
     * @param        $page
     * @param string $searchedTitle
     *
     * @return array
     */
    public function getOrderList($status, $page, $searchedTitle = '')
    {
        (new ParameterMustBePositiveInteger())->scene('order')->goCheck();
        return OrderModel::getOrderList($status, $page, $searchedTitle);
    }

    /**
     * @Desc 根据订单ID查询订单数据
     *
     * @param $id
     *
     * @return array
     */
    public function getOrderDetail($id)
    {
        (new ParameterMustBePositiveInteger())->scene('id')->goCheck();
        return OrderModel::getOrderDetail($id);
    }

    /**
     * @Desc 下单
     * @return array
     */
    public function placeOrder()
    {
        (new OrderValidate())->goCheck();
        $order = Request::instance()->post();
        return (new OrderService($order))->placeOrder();
    }

    /**
     * @Desc 下单 - 先下单再写入
     * @return array
     */
    public function placeOrder2()
    {
        (new OrderValidate())->goCheck();
        $order = Request::instance()->post();
        return (new Order2Service($order))->placeOrder();
    }

    /**
     * @Desc 取消订单
     *
     * @param $id
     *
     * @return SuccessMessage
     */
    public function cancelOrder($id)
    {
        (new ParameterMustBePositiveInteger())->scene('id')->goCheck();
        OrderModel::cancelOrder($id);
        $this->generatePaymentCancelData($id);
        return new SuccessMessage();
    }

    /**
     * @Desc 获取退款订单列表
     *
     * @param $page
     *
     * @return array
     */
    public function getRefundList($page)
    {
        (new ParameterMustBePositiveInteger())->scene('refund')->goCheck();
        return OrderModel::getRefundList($page);
    }

    /**
     * @Desc 获取退款订单详情
     *
     * @param $id
     *
     * @return array
     */
    public function getRefundDetail($id)
    {
        (new ParameterMustBePositiveInteger())->scene('id')->goCheck();
        return OrderModel::getRefundDetail($id);
    }

    /**
     * @Desc 更新退款订单
     *
     * @param $id
     *
     * @return SuccessMessage
     */
    public function updateRefundStatus($id)
    {
        (new ParameterMustBePositiveInteger())->scene('id')->goCheck();
        OrderModel::updateRefundStatus($id);
        return new SuccessMessage();
    }

    /**
     * @Desc 传递订单给收银系统
     *
     * @param $id
     *
     * @return mixed
     */
    public function generatePaymentOrderData($id)
    {
        $field = 'order_sn, company_id, total_amount, create_time, driving_license_id, subscribe_date, subscribe_code';
        $order = Db::name('order')->field($field)->where('order_id', '=', $id)->find();
        $license = Db::name('driving_license')->field('user_name, license_number, remarks')->where('id', '=', $order['driving_license_id'])->find();
        $data = [
            'order_id'    => $order['order_sn'], // 预约平台订单号
            'yuyue_mid'   => $order['company_id'], // 检车站ID
            'goods_price' => $order['total_amount'], // 订单金额
            // 'goods_price' => 0.01, // 订单金额
            'add_time'    => $order['create_time'], // 订单创建时间
            'car_master'  => $license['user_name'], // 车主姓名
            'car_num'     => $license['license_number'], // 车牌号
            'yuyue_time'  => $order['subscribe_date'], // 预约日期
            'yuyue_code'  => $order['subscribe_code'], // 预约码
            'other'       => $license['remarks'] ?: '', // 备注
            'new_param'   => 2, // 新的预约平台
        ];
        $url = Config::get('setting.add_order_url'); // 生产环境接口
        // $url = Config::get('setting.test_add_order_url'); // 开发环境接口
        return $this->sendOrderDataToPayment($url, $data);
    }

    /**
     * @Desc 传递取消订单给收银系统
     *
     * @param $id
     *
     * @return mixed
     */
    public function generatePaymentCancelData($id)
    {
        $order = Db::name('order')->field('order_sn, cancel_time')->where('order_id', '=', $id)->find();
        $data = [
            'order_id'  => $order['order_sn'], // 预约平台订单号
            'type'      => PaymentEnum::SEND_CANCELED, // 类型,1=支付，2=退款, 3=取消
            'paytime'   => time(), // 支付时间
            'new_param' => 2, // 新的预约平台
        ];
        $url = Config::get('setting.edit_order_url'); // 生产环境接口
        // $url = Config::get('setting.test_edit_order_url'); // 开发环境接口
        return $this->sendOrderDataToPayment($url, $data);
    }

    /**
     * @Desc 从收银系统接收支付订单数据
     * @return array|string
     */
    public function receivePayDataFromPayment()
    {
        $param = Request::instance()->param();
        if (!array_key_exists('order_sn', $param) || !array_key_exists('type', $param) || !array_key_exists('order_price', $param) || !array_key_exists('pay_time', $param)) {
            return [
                'code' => 0,
                'msg'  => '缺少参数',
            ];
        }
        $order = Db::name('order')->field('user_weixin_id, order_id')->where('order_sn', '=', $param['order_sn'])->find();
        if (!$order) {
            return [
                'code' => 0,
                'msg'  => '订单号错误',
            ];
        }
        Db::startTrans();
        try {
            $orderData = $memberData = [];
            $price = (int)$param['order_price'];
            switch ($param['type']) {
                // 支付
                case PaymentEnum::RECEIVE_PAY:
                    $orderData = [
                        'pay_time'     => $param['pay_time'],
                        'order_status' => OrderStatusEnum::PAID,
                        'pay_status'   => PayStatusEnum::PAID,
                    ];
                    // 生成积分数据
                    $memberData = [
                        'user_weixin_id' => $order['user_weixin_id'],
                        'number'         => $price,
                        'type'           => MemberLogEnum::INCREASE,
                        'get_from'       => MemberLogEnum::FROM_CONSUMPTION,
                    ];
                    // 添加积分记录
                    MemberLog::insertMemberData($memberData);
                    // 增加积分
                    Db::name('user_weixin')->where('id', '=', $order['user_weixin_id'])->setInc('member', $price);
                    break;
                // 退款中
                case PaymentEnum::RECEIVE_REFUNDING:
                    $orderData = [
                        'refund_status' => RefundStatusEnum::REFUNDING,
                    ];
                    $refundData = [
                        'order_id'      => $order['order_id'],
                        'refund_status' => RefundStatusEnum::REFUNDING,
                        'do_time'       => $param['pay_time'],
                    ];
                    RefundLog::create($refundData);
                    break;
                // 已退款
                case PaymentEnum::RECEIVE_REFUNDED:
                    $orderData = [
                        'refund_status' => RefundStatusEnum::REFUNDED,
                        'order_status'  => OrderStatusEnum::CANCELLED,
                        'cancel_time'   => $param['pay_time'],
                    ];
                    // 生成积分数据
                    $memberData = [
                        'user_weixin_id' => $order['user_weixin_id'],
                        'number'         => $price,
                        'type'           => MemberLogEnum::REDUCE,
                        'get_from'       => MemberLogEnum::FROM_REBACK,
                    ];
                    // 添加积分记录
                    MemberLog::insertMemberData($memberData);
                    // 增加积分
                    Db::name('user_weixin')->where('id', '=', $order['user_weixin_id'])->setDec('member', $price);
                    $refundData = [
                        'order_id'      => $order['order_id'],
                        'refund_status' => RefundStatusEnum::REFUNDED,
                        'do_time'       => $param['pay_time'],
                    ];
                    RefundLog::create($refundData);
                    break;
            }
            OrderModel::updateOrder($orderData, $param['order_sn']);
            Db::commit();
            return [
                'code' => 1,
                'msg'  => 'ok',
            ];
        } catch (Exception $e) {
            // 出错啦，处理下吧
            Db::rollback();
            Log::error($e);
            return [
                'code' => 0,
                'msg'  => $e->getMessage(),
            ];
        }
    }

    /**
     * @Desc 向收银系统发送订单数据
     *
     * @param string $url  接口地址
     * @param array  $data 要发送的数据
     *
     * @return mixed
     */
    private function sendOrderDataToPayment($url, $data)
    {
        return (new HttpRequest())->post($url, $data)->json(true);
    }

    /**
     * @Desc 向image表添加数据，同时将image_id加入行驶证表
     * @return string
     */
    public function insertImage()
    {
        //insert into `cd_image`(`url`, `create_time`, `update_time`) values('', '1594887844', '1594887844')
        $orders = db('order')->field('order_id, ld_image, driving_license_id')->where('ld_image', '<>', '')->where('order_id', 'between', [1, 10000])->select();
        foreach ($orders as $key => $order) {
            $insertData = [
                'url'         => $order['ld_image'],
                'create_time' => 1599723061,
                'update_time' => 1599723061,
            ];
            $image_id = db('image')->insertGetId($insertData);
            db('driving_license')->where('id', '=', $order['driving_license_id'])->setField('image_id', $image_id);
        }
        return '成功';
    }
}